<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="10">
        <el-col :span="12">
          <!-- 搜索框栏 -->
          <el-input
            clearable
            placeholder="请输入内容"
            v-model="userListParam.query"
            @clear="reqUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="reqUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="isDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表数据展示 -->
      <el-table :data="userListData" style="width: 100%" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="手机号码"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="160"></el-table-column>
        <el-table-column prop label="状态">
          <template slot-scope="scope">
            <el-switch @change="userStateChange(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop label="操作">
          <template slot-scope="scope" width="190">
            {{ scope.row.lenght}}
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editUserDataDialog(scope.row)"
              size="mini"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"
              size="mini"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userListParam.pagenum"
        :page-sizes="[1, 2, 3, 5, 10]"
        :page-size="userListParam.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dataTotal"
      ></el-pagination>
    </el-card>
    <!-- 添加用户弹窗 -->
    <el-dialog
      title="添加用户"
      :visible.sync="isDialogVisible"
      width="50%"
      @close="addUserDialogClosed"
    >
      <el-form
        ref="addUserFormRef"
        :rules="addUserFormRules"
        :model="addUserForm"
        label-width="100px"
      >
        <el-form-item prop="username" label="用户名：">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱：">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号码：">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码：">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户弹窗 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editUserDialogClosed"
    >
      <el-form
        ref="editUserFormRef"
        :rules="editUserFormRules"
        :model="editUserForm"
        label-width="100px"
      >
        <el-form-item prop="username" label="用户名：">
          <el-input v-model="editUserForm.username" :disabled="false"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱：">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号码：">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色弹窗 -->
    <el-dialog
      title="分配角色"
      :visible.sync="soleDialogVisible"
      width="50%"
      @close="soleDialogVisibleClosed"
    >
      <div>
        <p>当前用户：{{ userinfo.username }}</p>
        <p>当前角色：{{ userinfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleValue" placeholder="请选择">
            <el-option
              v-for="item in rolesDataList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="soleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click='selectRoleOK'>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入正确的邮箱"));
    };
    // 验证手机号码规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入正确的手机号码"));
    };
    return {
      userListParam: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      userListData: [],
      dataTotal: 0,
      isDialogVisible: false,
      editDialogVisible: false,
      soleDialogVisible: false,
      userinfo: {},
      // 添加用户的表单数据
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 修改用户的表单数据
      editUserForm: {
        id: 0,
        username: "",
        email: "",
        mobile: ""
      },
      rolesDataList:[],
      selectRoleValue:'',
      // 添加用户数据表单的验证条件
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在3到8个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // { min: 11, max: 11, message: "请输入正确手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ]
      },
      // 修改用户数据表单的验证条件
      editUserFormRules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // { min: 11, max: 11, message: "请输入正确手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.reqUserList();
  },
  methods: {
    //   监听分页显示的长度
    handleSizeChange(pageSize) {
      console.log("==分页显示的长度===>" + pageSize);
      this.userListParam.pagesize = pageSize;
      this.reqUserList();
    },
    //   当前分页 的页数
    handleCurrentChange(pageNum) {
      console.log("==当前分页的页数===>" + pageNum);
      this.userListParam.pagenum = pageNum;
      this.reqUserList();
    },
    // 用户状态变化回调
    userStateChange(data) {
      this.$httpReq
        .put(`users/${data.id}/state/${data.mg_state}`)
        .then(res => {
          // {"data":{"id":502,"rid":34,"username":"linken","mobile":"1213213123","email":"asdf@qq.com","mg_state":1},"meta":{"msg":"设置状态成功","status":200}}
          console.log("状态变化==>" + JSON.stringify(res));
          var msg = res.meta.msg;
          if (res.meta.status == 200) {
            return this.$message.success(msg);
          } else {
            data.mg_state = !data.mg_state;
            return this.$message.error(msg);
          }
        })
        .catch(error => {
          data.mg_state = !data.mg_state;
          return this.$message.error(error.data);
        });
    },

    //请求用户数据列表
    reqUserList() {
      this.$httpReq
        .get("users", { params: this.userListParam })
        .then(res => {
          console.log("===用户列表数据=>" + JSON.stringify(res));
          if (res.meta.status == 200) {
            this.userListData = res.data.users;
            this.dataTotal = res.data.total;
          } else {
            var msg = res.meta.msg;
            this.$message.error(msg);
          }
        })
        .catch(error => {
          this.$message.error(JSON.stringify(error.data));
        });
    },
    //获取所有角色
    reqAllSoles() {
       this.$httpReq.get("roles").then(res => {
        if (res.meta.status == 200) {
          this.rolesDataList = res.data;
        } else {
          var msg = res.meta.msg;
          this.$message.error(msg);
        }
      });
    },
    //分配角色请求
    reqSetSoles() {
       this.$httpReq.put(`users/${this.userinfo.id}/role`,{rid:this.selectRoleValue}).then(res => {
         var msg = res.meta.msg;
        if (res.meta.status == 200) {
           this.$message.success(msg);
       this.reqUserList();
           this.soleDialogVisible = false;
        } else {
          this.$message.error(msg);
        }
      }).catch(err => {
         this.$message.error(err);
      });
    },
    // 添加用户弹窗关闭回调
    addUserDialogClosed() {
      this.$refs.addUserFormRef.resetFields();
    },
    // 确认添加用户数据
    addUserData() {
      this.$refs.addUserFormRef.validate(valid => {
        if (!valid) return;
        this.$httpReq
          .post("users", this.addUserForm)
          .then(res => {
            var msg = res.meta.msg;
            if (res.meta.status == 201) {
              this.$message.success("添加成功");
              this.isDialogVisible = false;
              this.reqUserList();
            } else {
              this.$message.error(msg);
            }
          })
          .catch();
      });
    },
    // 修改用户弹窗关闭回调
    editUserDialogClosed() {
      this.$refs.editUserFormRef.resetFields();
    },
    //修改用户数据的弹窗
    editUserDataDialog(data) {
      this.editUserForm.id = data.id;
      this.editUserForm.username = data.username;
      this.editUserForm.email = data.email;
      this.editUserForm.mobile = data.mobile;
      this.editDialogVisible = true;
    },
    //修改用户数据
    editUserData() {
      this.$refs.editUserFormRef.validate(valid => {
        if (!valid) return;
        this.$httpReq
          .put(`users/${this.editUserForm.id}`, this.editUserForm)
          .then(res => {
            var msg = res.meta.msg;
            console.log("===msg=>" + msg);
            if (res.meta.status == 200) {
              this.$message.success("修改成功");
              this.editDialogVisible = false;
              this.reqUserList();
            } else {
              this.$message.error(msg);
            }
          })
          .catch();
      });
    },
    //删除用户
    deleteUser(uId) {
      console.log(uId);
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$httpReq.delete(`users/${uId}`).then(res => {
            var msg = res.meta.msg;
            console.log("===msg=>" + msg);
            if (res.meta.status == 200) {
              this.$message.success("删除成功");
              this.reqUserList();
            } else {
              this.$message.error(msg);
            }
          });
        })
        .catch(err => {
          console.log(err);
          this.$message("取消删除成功！");
        });
    },
    //开启分配角色弹窗
    showSoleDialog(data) {
      this.userinfo = data;
      this.reqAllSoles();
      this.soleDialogVisible = true;
    },
    //分配角色弹窗关闭监听
    soleDialogVisibleClosed() {
      this.selectRoleValue = ""
      this.userinfo = [];
    },
    //确认分配角色
    selectRoleOK()
    {
      if(!this.selectRoleValue)
      {
       return this.$message.error('请选择要分配的角色');
      }
      this.reqSetSoles();
    }
  }
};
</script>

<style>
</style>



